package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageRsult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageRsult search(RequestParams params) {
        try {
            //设置请求
            SearchRequest searchRequest = new SearchRequest("hotel");

            functionScoreQuery(params, searchRequest);

            String location = params.getLocation();

            if (location != null && !"".equals(location)) {
                searchRequest.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }

            Integer page = params.getPage();

            Integer size = params.getSize();

            searchRequest.source().from((page - 1) * size).size(size);

            //发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            return getResponseValue(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void functionScoreQuery(RequestParams params, SearchRequest searchRequest) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //构造语句
        String key = params.getKey();

        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        String city = params.getCity();
        String brand = params.getBrand();
        String starName = params.getStarName();
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();


        if (city != null && !"".equals(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        if (brand != null && !"".equals(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        if (starName != null && !"".equals(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        FunctionScoreQueryBuilder functionscoreQuery = QueryBuilders.functionScoreQuery(
                //查询条件
                boolQuery,
                //创建function数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //创建元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //查询过滤
                                QueryBuilders.termQuery("isAD", true),
                                //权重赋值，默认是乘
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }

        );

        searchRequest.source().query(functionscoreQuery);
    }

    private static PageRsult getResponseValue(SearchResponse response) {
        SearchHits hits = response.getHits();

        long total = hits.getTotalHits().value;

        SearchHit[] hitsHits = hits.getHits();

        ArrayList<HotelDoc> list = new ArrayList<>();
        for (SearchHit hitsHit : hitsHits) {

            String source = hitsHit.getSourceAsString();

            HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);

            Object[] sortValues = hitsHit.getSortValues();

            if (sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }

            list.add(hotelDoc);
        }

        return new PageRsult(total, list);
    }

    @Override
    public Map<String, List<String>> filter(RequestParams params) {
        HashMap<String, List<String>> map = new HashMap<>();
        try {
            //hotel索引库聚合
            SearchRequest searchRequest = new SearchRequest("hotel");
            functionScoreQuery(params, searchRequest);
            //设置文本大小
            searchRequest.source().size(0);

            Aggregations aggregations = getAggregations(searchRequest, "brandAggs", "brand");
            ArrayList<String> list = getList(aggregations, "brandAggs");
            map.put("brand", list);

            Aggregations aggregations2 = getAggregations(searchRequest, "cityAggs", "city");
            ArrayList<String> list2 = getList(aggregations2, "cityAggs");
            map.put("city", list2);

            Aggregations aggregations3 = getAggregations(searchRequest, "starAggs", "starName");
            ArrayList<String> list3 = getList(aggregations3, "starAggs");
            map.put("starName", list3);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private static ArrayList<String> getList(Aggregations aggregations, String name) {
        //必须用Terms类型进行接受，使用快捷键的类型不对
        Terms brandAggs = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = brandAggs.getBuckets();
        ArrayList<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    private Aggregations getAggregations(SearchRequest searchRequest, String name, String feild) throws IOException {

        //构建聚合函数
        searchRequest.source().aggregation(AggregationBuilders
                //设置聚合查询方式，以及该聚合名称
                .terms(name)
                //设置聚合字段
                .field(feild));

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        return response.getAggregations();
    }

    @Override
    public List<String> getSuggestion(String key) {
        ArrayList<String> list = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest("hotel");
            //构建自动补全语句
            SuggestBuilder suggestBuilder = new SuggestBuilder().addSuggestion(
                    //自定义名称
                    "mySuggestion",
                    //自动补全的字段
                    SuggestBuilders.completionSuggestion("suggestion")
                            //关键字
                            .prefix(key)
                            //跳过重复
                            .skipDuplicates(true)
                            //获取前10条数据
                            .size(10));

            searchRequest.source().suggest(suggestBuilder);

            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //解析回应
            Suggest suggest = response.getSuggest();

            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");

            for (CompletionSuggestion.Entry.Option option : mySuggestion.getOptions()) {
                String text = option.getText().toString();
                list.add(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void addById(Long id) {
        try {
            Hotel hotel = getById(id);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest indexRequest = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("hotel",id.toString());
            client.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
